package com.lsz.flight_system.service.Impl;

import com.lsz.flight_system.entity.Admin;
import com.lsz.flight_system.repository.AdminRepository;
import com.lsz.flight_system.service.AdminService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class AdminServiceImpl implements AdminService {

    @Autowired
    AdminRepository adminRepository;


    @Override
    public List<Admin> findAllAdmin(Map<String,Object> map) {
        return adminRepository.findAll(new Specification<Admin>() {
            @Override
            public Predicate toPredicate(Root<Admin> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                List<Predicate> predicateList = new ArrayList<>();

                if (map.containsKey("username") && !StringUtils.isEmpty(map.get("username"))){
                    predicateList
                            .add(cb.like(root.get("username"),"%"+map.get("username").toString()+"%"));
                }

                Predicate[] predicateArr = new Predicate[predicateList.size()];
                return cb.and(predicateList.toArray(predicateArr));
            }
        });
    }

    @Override
    public boolean addAdmin(Admin admin) {
        String username = admin.getUsername();
        if (adminRepository.findAdminByUsername(username)!=null){
            return false;
        }else {
            adminRepository.save(admin);
            return true;
        }
    }

    @Override
    public boolean delAdminByUsername(String username) {
        Admin admin = adminRepository.findAdminByUsername(username);
        adminRepository.delete(admin);
        if (adminRepository.findAdminByUsername(username)==null){
            return true;
        }
        return false;
    }

    @Override
    public Admin getAdminByUsername(String username) {
        return adminRepository.findAdminByUsername(username);
    }
}
